'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { ajax } from 'utils/index';
import {addItem,setPageId,closeSystemDialog} from '../../actions/index';
import DndBody from '../DndBody/index';
import * as PREVIEW from '../TOOL/Preview/index';
import { Dialog  } from 'qnui';
import SystemDialog from 'components/system-dialog/index';
import './index.scss';

class Main extends React.Component {

	constructor(props) {
		super(props);
		this.state={
			private_components:[]
		}
		let page_id = (this.getQueryString("page_id"));
		this.props.dispatch(setPageId(page_id));
		ajax({
		  api: 'getComponents',
		  method: 'GET',
		  data:{page_id}
		},(json) => {
			const private_components=[];
			json.components.map((comp,key)=>{
				switch(comp.code){
					case "single_image":
						comp.preview=<PREVIEW.ToolSingleImagePreview dataId={key+3} />;
					break;
					case "double_images":
						comp.preview=<PREVIEW.ToolDoubleImagesPreview dataId={key+3} />;
					break;
					case "triple_images":
						comp.preview=<PREVIEW.ToolTripleImagesPreview dataId={key+3} />;
					break;
					case "countdown_prom_v1":
						comp.preview=<PREVIEW.CountdownPromV1Preview dataId={key+3} />;
					break;
					case "countdown_items_v1":
						comp.preview=<PREVIEW.CountdownItemsV1Preview dataId={key+3} />;
					break;
					case "shop_title_v1":
						comp.preview=<PREVIEW.ToolShopTitlePreview dataId={key+3} />;
					break;
				}
				if(comp.model_private){
					private_components.push(comp.code);
				}
				this.props.dispatch(addItem(comp));
			});
			this.setState({private_components});
		},(json) => {
			  //失败后
			  //(json.code==53) W2超时
			Dialog.alert({content:"抱歉，获取页面插件失败，请重试"});
		});
	}
	getQueryString(name) { 
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
        var r = window.location.search.substr(1).match(reg); 
        if (r != null) return unescape(r[2]); 
        return null; 
    } 
	closeSystemDialog(){
	  this.props.dispatch(
			closeSystemDialog()
	  );
	}
	render() {
		return (
		  <div className="todoMVC-container">
			<SystemDialog 
				loginError={this.props.todoMVC[0].loginError}	
				creating={this.props.todoMVC[0].creating}
				message={this.props.todoMVC[0].message}
				error={this.props.todoMVC[0].error}
				onClose={this.closeSystemDialog.bind(this)}
				/>
			<DndBody dataSource={this.props.todoMVC} component={this.props.component} dispatch={this.props.dispatch} private_components={this.state.private_components}/>
		  </div>
		);
	}
}


// map state to props
export default connect((state)=> {
  return {
    todoMVC:state.todoMVCReducer,
	component:state.component
  }
})(Main);
